const app = getApp();
const utils = require('../../utils/utils.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userinfo: {},
    devSn: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userinfo = app.globalData.userInfo;
    // console.log(JSON.stringify(userinfo));
    if (userinfo.id != null) {
      this.setData({
        userinfo: userinfo
      })
    } else {
      // 未查询到对应的用户信息
      let openid = app.globalData.openID;
      // console.log("onLoad openid==>" + openid);
      if (openid == 'miand' || openid == '') {
        // 需要用户授权登录
        this.getWxOpenid();
      } else {
        // 通过openid来获取用户信息
        this.getUseInfo();
      }
    }
  },

  // ============== 登录操作 ==============
  getWxOpenid() {
    let that = this;
    wx.login({
        success(res) {
            if (res.code) {
                utils.httpRequest('/login', {
                    code: res.code
                }, function (res) {
                    if (res.data.openid) {
                        wx.setStorageSync("openID", res.data.openid);
                        app.globalData.openID = res.data.openid;
                        let scene = 3;
                        that.userIsAuth(scene);
                    }
                })
            }
        }
    })
  },


  // ===================== 判断用户是否授权 =============================
  userIsAuth(scene) {
    let that = this;
    let isAuth = this.data.isAuth;
    utils.httpRequest('/checkAuth', {}, function (res) {
        // console.log("scene-->" + scene);
        // console.log("userIsAuth-->" + JSON.stringify(res));
        if (res.code == 1) {
            if (res.data.is_auth == 1) { //已授权
                that.getUseInfo();
                if (scene == 1) {
                    //跳转用户界面
                    wx.navigateTo({
                        url: '../user/user'
                    });
                }
            } else {
                // 未获取到用户昵称信息，需要让用户再次授权
                if (scene == 3) {
                    wx.navigateTo({
                        url: '../authorization/authorization?scene=3'
                    });
                }
            }
        }
    })
  },

  // ============ 获取用户信息 ================
  getUseInfo: function () {
    wx.showLoading({
        title: 'loading...',
        mask: true
    });
    let that = this;
    utils.httpRequest('/getInfo', {}, function (res) {
        wx.hideLoading();
        if (res.code == 1) {
            that.setData({
                userinfo: res.data.user
            })
        }
    })
  },

  /**
   * 点击扫一扫
   */
  clickScan: function(){
    let that = this;
    wx.scanCode({
      onlyFromCamera: true,
      success(res) {
          if (res.result) {
              let sn = res.result.split('/').pop();
              wx.showLoading({
                  title: 'loading...',
                  mask: true
              })
              utils.httpRequest('/checkDeviceType', {
                  sn: sn
              }, function (res) {
                  wx.hideLoading();
                  if (res.code == 1) {
                    that.setData({
                      devSn: sn
                    })
                  }
              })
          } else {
              wx.showToast({
                  title: "扫码失败",
                  icon: 'none',
                  duration: 2000
              });
          }
      },
      complete: function () {
        
      }
    })
  },

  /**
   * 表单提交
   * @param {*} e 
   */
  submitApply: function(e){
    let data = e.detail.value;
    let sn = data.sn;
    let true_name = data.true_name;
    let phone = data.phone;
    if (sn == "" || sn == null) {
      wx.showToast({
        title: "请填写设备编号!",
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (true_name == "" || true_name == null) {
      wx.showToast({
        title: "请填写真实姓名!",
        icon: 'none',
        duration: 2000
      });
      return;
    }
    if (phone == "" || phone == null) {
      wx.showToast({
        title: "请填写手机号码!",
        icon: 'none',
        duration: 2000
      });
      return;
    }
    let flag = this.checkPhone(phone);
    if (!flag) {
      wx.showToast({
        title: "手机号码不合法!",
        icon: 'none',
        duration: 2000
      });
      return;
    }
    wx.showLoading({
      title: 'loading...',
      mask: true
    })
    utils.httpRequest('/submitApply', {
        sn: sn,
        true_name: true_name,
        phone: phone
    }, function (res) {
        wx.hideLoading();
        if (res.code == 1) {
          wx.showToast({
            title: "提交申请成功",
            icon: 'none',
            duration: 2000
          });
        }
    })
  },
  // 校验手机号
  checkPhone(phone) {
    const regu=/^((13[0-9])|(14[5-9])|(15([0-3]|[5-9]))|(16[6-7])|(17[1-8])|(18[0-9])|(19[1|3])|(19[5|6])|(19[8|9]))\d{8}$/;
    return regu.test(phone);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})